package com.zx.znav.controller.user;

import com.zx.znav.bean.UserDescription;
import com.zx.znav.constant.Constants;
import com.zx.znav.controller.vo.UserVO;
import com.zx.znav.service.LinkService;
import com.zx.znav.service.LinkStarService;
import com.zx.znav.service.UserDescriptionService;
import com.zx.znav.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 个人空间
 * @since 2023-08-15 19:42
 */
@Controller
@RequestMapping("/user/space")
public class SpaceController {
    @Autowired
    private LinkStarService linkStarService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private UserDescriptionService userDescriptionService;

    @GetMapping
    public String index() {
        return "user-space";
    }

    //加载页面数据
    @PostMapping
    public String loadContent(@RequestParam(required = false, defaultValue = "1") Integer item, Model model) {
        model.addAttribute(Constants.ITEM_KEY, item);
        UserVO user = UserHolder.getUser();
        if (user == null) {
            return "user-space :: notLogin";
        }
        model.addAttribute(Constants.MODEL_USER_KEY, user);
        if (item == 1) {
            //查个人描述
            UserDescription description = userDescriptionService.getDescriptionByUserId(UserHolder.getUser().getId());
            if (description != null)
                model.addAttribute(Constants.DESCRIPTION_KEY, description.getContent());
        } else if (item == 2) {//站内消息

        } else if (item == 3) {//我的收藏
            //收藏链接
            List<Integer> linkIds = linkStarService.listStarLink(user.getId());
            if (linkIds.size() > 0)
                model.addAttribute(Constants.LinKS_KEY, linkService.listByIds(linkIds));
        } else if (item == 4) {
            //3402747477@qq.com -> 3***7@qq.com
            model.addAttribute("email", dealEmail(user.getEmail()));
        }
        return "user-space :: content";
    }
    private String dealEmail(String email){
        return email.charAt(0) + "****" + email.charAt(email.indexOf("@") - 1) + email.substring(email.indexOf("@"));
    }

    @GetMapping("/avatar")
    public String loadAvatar(Model model) {
        model.addAttribute(Constants.MODEL_USER_KEY, UserHolder.getUser());
        return "user-space :: userAvatar";
    }
}
